<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\DB;


class Access
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $admin_user = session('admin_user');
        foreach ($admin_user as $val){
            $user_id = $val->id;
        }
        if($user_id!=1){
            $route =  \Request::getRequestUri();
            $res =DB::table('admin_node')
                ->join('admin_access','admin_node.id','admin_access.node_id')
                ->join('admin_role','admin_role.id','admin_access.role_id')
                ->join('admin_role_user','admin_role_user.role_id','admin_role.id')
                ->join('admin_user','admin_user.id','admin_role_user.user_id')
                ->where('admin_node.title',$route)->where('admin_user.id',$user_id)->first;
            if($res){
                return $next($request);
            }else{
                return redirect('/admin/error');
            }
        }else{
            return $next($request);
        }
    }
}
